package com.xin.bi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.bi.constant.UserConstant;
import com.xin.bi.exception.BusinessException;
import com.xin.bi.model.entity.User;
import com.xin.bi.model.vo.LoginUserVO;
import com.xin.bi.service.UserService;
import com.xin.bi.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
* @author 鑫
* @description 针对表【user(用户)】的数据库操作Service实现
* @createDate 2023-07-18 16:37:14
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录 单点登录
     * @param userAccount
     * @param userPassword
     * @param httpServletRequest
     * @return
     */
    @Override
    public LoginUserVO login(String userAccount, String userPassword, HttpServletRequest httpServletRequest) {
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException("账号密码有误");
        }
        // todo 账号密码 长度 特殊字符校验
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",userAccount);
        queryWrapper.eq("user_password",userPassword);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            throw new BusinessException("登录失败");
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user,loginUserVO);
        httpServletRequest.getSession().setAttribute(UserConstant.USER_LOGIN_STATE,loginUserVO);
        return loginUserVO;
    }


    /**
     * 获取用户登录的信息
     * @param httpServletRequest
     * @return
     */
    public LoginUserVO getLoginUserVO(HttpServletRequest httpServletRequest){
        LoginUserVO loginUserVO =(LoginUserVO) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (loginUserVO==null){
            throw new BusinessException("未登录");
        }
        return loginUserVO;
    }
}




